import 'dart:async';

import 'package:aio/aio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/config/app_data_config.dart';
import 'package:app/src/http/bean/user.dart';
import 'package:app/src/http/model/sms_model.dart';
import 'package:app/src/http/model/user_model.dart';
import 'package:app/src/manager/user_manager.dart';
import 'package:app/src/ui/app_ui.dart';
import 'package:app/src/http/bean/http_data.dart';
import 'package:app/src/http/model/config_model.dart';
import 'package:app/src/ui/dialog/dailog.dart';
import 'package:app/src/ui/route/helper/route_helper.dart';
import 'package:app/src/utils/image_path_utils.dart';

///手机验证码验证
class SmsMobileRoute extends StatefulWidget {
  @override
  _State createState() => _State();
  static bool isShow = false;
}

class _State extends State<SmsMobileRoute> {
  _Presenter presenter = _Presenter();

  @override
  void initState() {
    super.initState();
    SmsMobileRoute.isShow = true;
    Future.delayed(Duration(milliseconds: 200)).then((e) {
      ///验证手机号
      presenter?.validationMobile(context);
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    SmsMobileRoute.isShow = false;
  }

  @override
  Widget build(BuildContext context) {
    px.init(context);
    var scaffold = Scaffold(
      backgroundColor: AppColors.backgroundColorWithWhite,
      appBar: AppBar(
        backgroundColor: AppColors.backgroundColorWithWhite,
        elevation: 0,
        leading: AppUi.getBack(context, () {
          return false;
        }),
        centerTitle: false,
        leadingWidth: 36,
        titleSpacing: 0,
        //手机号验证
        title: Text(
          AppStrings.of(context).MobilePhone,
          style: AppStyle.textStyleWithTitle(),
        ),
      ),
      body: Material(
          color: AppColors.backgroundColorWithWhite, child: _body(context)),
    );
    return WillPopScope(
      child: scaffold,
      onWillPop: () async {
        return true;
      },
    );
  }

  var _marginTop = 24.0;

  Widget _body(BuildContext context) {
    return Scrollbar(
      child: SingleChildScrollView(
        physics: BouncingScrollPhysics(),
        child: Column(
          children: [
            //手机号
            Center(
              child: Container(
                margin: AppEdgeInsets.marginWithItem(
                    top: _marginTop, left: px.x(48), right: px.x(48)),
                child: _mobile(),
              ),
            ),
            //验证码
            Center(
              child: Container(
                margin: AppEdgeInsets.marginWithItem(
                    top: _marginTop, left: px.x(48), right: px.x(48)),
                child: _sms(),
              ),
            ),
            //验证
            _validation()
          ],
        ),
      ),
    );
  }

  //手机号
  TextEditingController? _mobileTextEditingController;

  Widget _mobile() {
    if (_mobileTextEditingController == null) {
      _mobileTextEditingController =
          TextEditingController(text: UserManager.getUserInfo()?.MobileNum);
    }
    return StatefulBuilder(
      builder: (context, setState) {
        return TextFormField(
          cursorColor: AppColors.themeColorWithServerAdress,
          //鼠标颜色
          controller: _mobileTextEditingController,
          //文本控制器
          onChanged: (value) {
            //文本发生变化
            setState(() {});
          },
          readOnly: true,
          //只读模式
          decoration: InputDecoration(
              hintText: AppStrings.of(context).mobile, //手机号
              focusedBorder: UnderlineInputBorder(
                  borderRadius: BorderRadius.all(Radius.circular(0)),
                  borderSide: BorderSide(
                      color: AppColors.themeColorWithServerAdress, width: 1)),
              prefixIcon: Container(
                child: Center(
                  child: Image.asset(
                    ImagePathUtils.getPathWithImageMobile("mobile.png"),
                    color: Colors.blueAccent,
                    width: 33,
                  ),
                ),
                width: 60,
              ),
              //fixme 获取手机号
              suffixIcon: Container(
                width: 120,
                //height: 40,
                child: InkWell(
                  child: Center(
                    child: Text(
                      AppStrings.of(context).getmobile,
                      style: TextStyle(color: Colors.blueAccent),
                    ),
                  ),
                  onTap: () {
                    //获取手机号
                    presenter?.getpersoninfo(context, (value) {
                      if (value != null) {
                        _mobileTextEditingController?.text = value!.MobileNum;
                      }
                    });
                  },
                ),
              )),
        );
      },
    );
  }

  //验证码
  TextEditingController? _smsTextEditingController;

  //短信是否已发送
  bool _isSendSms = false;

  //计时器
  int _count = 60;

  Widget _sms() {
    if (_smsTextEditingController == null) {
      _smsTextEditingController = TextEditingController(text: presenter?.sms);
    }
    return StatefulBuilder(
      builder: (context, setState) {
        return TextFormField(
          cursorColor: AppColors.themeColorWithServerAdress,
          //鼠标颜色
          controller: _smsTextEditingController,
          //文本控制器
          onChanged: (value) {
            //文本发生变化
            setState(() {
              presenter?.sms = value;
            });
          },
          decoration: InputDecoration(
              hintText: AppStrings.of(context).sms, //验证码
              focusedBorder: UnderlineInputBorder(
                  borderRadius: BorderRadius.all(Radius.circular(0)),
                  borderSide: BorderSide(
                      color: AppColors.themeColorWithServerAdress, width: 1)),
              prefixIcon: Container(
                child: Center(
                  child: Image.asset(
                    ImagePathUtils.getPathWithImageMobile("sms_code.png"),
                    color: Colors.blueAccent,
                    width: 36,
                  ),
                ),
                width: 60,
              ),
              //发送验证码
              suffixIcon: Container(
                width: 120,
                //height: 40,
                child: InkWell(
                  child: Center(
                    child: Text(
                      _isSendSms
                          ? ("($_count)" + AppStrings.of(context).getsms)
                          : AppStrings.of(context).getsms,
                      style: TextStyle(
                          color: _isSendSms ? Colors.grey : Colors.blueAccent),
                    ),
                  ),
                  onTap: () {
                    //发送验证码
                    if (!_isSendSms) {
                      presenter?.getValidation(
                          context, _mobileTextEditingController?.text, (b) {
                        if (b) {
                          _isSendSms = true;
                          _count = 60;
                          Timer.periodic(Duration(seconds: 1), (timer) {
                            if (_count <= 0) {
                              timer.cancel(); //定时取消
                              _isSendSms = false;
                            }
                            _count--;
                            //刷新
                            if (mounted) {
                              setState(() {});
                            }
                          });
                          if (mounted) {
                            setState(() {});
                          }
                        }
                      });
                    }
                  },
                ),
              )),
        );
      },
    );
  }

  ///验证
  Widget _validation() {
    return Center(
      child: Container(
        margin: AppEdgeInsets.marginWithItem(top: _marginTop),
        child: MaterialButton(
          height: 55,
          minWidth: px.screenWidth(),
          onPressed: () {
            //print('点击事件${presenter.toString()}');
            presenter?.validation(context);
          },
          //label 右边控件（一般为文本），不能为空
          color: AppColors.themeColorWithServerAdress,
          //color 按钮颜色
          splashColor: Colors.black12,
          //splashColor 点击时，飞溅扩散的颜色
          //highlightColor: Colors.red, //highlightColor 点击时按钮颜色
          colorBrightness: Brightness.light,
          //colorBrightness 按钮亮度；Brightness.dark 暗系风格;Brightness.light 高亮(默认)
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(60))),
          //shape 形状
          textColor: Colors.white,
          //文本默认颜色
          child: Text(
            AppStrings.of(context).validation,
            style: AppStyle.textStyleWithButton(),
          ), //fixme 子控件
        ),
      ),
    );
  }
}

class _Presenter {
  //服务器验证码
  String? sms_server = null;

  //验证码
  String? sms = null;

  ///验证手机号
  void validationMobile(BuildContext context) {
    var Data = UserManager.getUserInfo();
    if (!RegexUtils.isTelMobile(Data?.MobileNum)) {
      AppDialog.showDialogWithInfo(context,
          content: AppStrings.of(context).boundmobile);
    }
  }

  ///获取用户信息
  void getpersoninfo(
      BuildContext context, ResponseCallbackWithT_<UserInfo> callback) {
    UserModel.getpersoninfo(context, true, (value) {
      if (value.isSuccessForData()) {
        //信息获取成功
        UserManager.setUserInfo(value.Data);
        callback?.call(value.Data);
        validationMobile(context);
      } else {
        AppDialog.showDialogWithInfo(context, content: value?.MsgDetail);
      }
    });
  }

  ///获取验证码
  ///MobileNum 手机号
  void getValidation(BuildContext context, String? MobileNum,
      ResponseCallbackWithBool? callback) {
    if (RegexUtils.isTelMobile(MobileNum)) {
      // var _sms_server = MathUtils.getTheRandomWithValidation();
      // SmsModel.getSmsCode(context, MobileNum!, _sms_server!, true, (value) {
      //   if (value?.success != null) {
      //     sms_server = _sms_server;
      //     callback?.call(value!.success!);
      //     //验证码发送成功
      //     Toast.showSuccess(
      //         AppStrings.of(context).GetValidationSuccess, context);
      //   }
      // });
      SmsModel.getSmsCodeWithServer(context, true, MobileNum!, (value) {
        if (value.isSuccessForData()) {
          sms_server = value.Data;
          callback?.call(true);
          //验证码发送成功
          Toast.showSuccess(
              AppStrings.of(context).GetValidationSuccess, context);
        } else {
          AppDialog.showDialogWithInfo(context, content: value.MsgDetail);
        }
      });
    } else {
      //手机号不正确
      AppDialog.showDialogWithInfo(context,
          content: AppStrings.of(context).MobileError);
    }
  }

  ///验证
  void validation(BuildContext context) {
    if (StringUtils.isNotEmpty(sms_server)) {
      if (sms_server?.trim() == sms?.trim()) {
        //保存已验证的手机号
        AppDataConfig.setMobile(UserManager.getUserInfo()?.MobileNum);
        //验证成功
        Toast.showSuccess(AppStrings.of(context).ValidationSuccess, context);
        //fixme 主页面
        AppRouteHelper.goMainRoute(context);
      } else {
        //验证码错误
        AppDialog.showDialogWithInfo(context,
            content: AppStrings.of(context).ValidationError);
      }
    } else {
      //请先获取验证码
      AppDialog.showDialogWithInfo(context,
          content: AppStrings.of(context).getvalidation);
    }
  }
}
